import 'dart:async';

import 'package:dartx/dartx.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:sgy_flutter/ble/ble_manager.dart';
import 'package:rxdart/rxdart.dart' as rx;

class BleConnectionView extends StatelessWidget {
  final BleManager? bleManager;
  final Widget Function(BluetoothConnectionState state) builder;
  final bool? initialData;

  const BleConnectionView(
      {super.key,
        required this.bleManager,
        required this.builder,
        this.initialData});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<BluetoothConnectionState>(
        initialData: bleManager?.connectionState.value,
        stream: bleManager?.connectionState.stream ??
            Stream.value(BluetoothConnectionState.disconnected),
        builder: (BuildContext context, AsyncSnapshot<BluetoothConnectionState> snapshot) {
          return builder(snapshot.data??BluetoothConnectionState.disconnected);
        });
  }
}

class BleConnectionView2 extends StatefulWidget {
  final BleManager? bleManager;
  final BleManager? rightBleManager;
  final Widget Function(BluetoothConnectionState leftState, BluetoothConnectionState rightState) builder;

  const BleConnectionView2({
    super.key,
    required this.rightBleManager,
    required this.bleManager,
    required this.builder,
  });

  @override
  State<StatefulWidget> createState() {
    return _BleStateView2State();
  }
}
class _BleStateView2State extends State<BleConnectionView2>{

  StreamSubscription? _subscription1;
  StreamSubscription? _subscription2;
  BluetoothConnectionState leftState = BluetoothConnectionState.disconnected;
  BluetoothConnectionState rightState = BluetoothConnectionState.disconnected;
  @override
  void initState() {
    leftState = widget.bleManager?.connectionState.value ?? BluetoothConnectionState.disconnected;
    rightState = widget.rightBleManager?.connectionState.value ?? BluetoothConnectionState.disconnected;
    _subscription1 = widget.bleManager?.connectionState.listen((value){
      setState(() {
        leftState = value;
      });
    });
    _subscription2 = widget.rightBleManager?.connectionState.listen((value){
      setState(() {
        rightState = value;
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    _subscription1?.cancel();
    _subscription2?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(leftState, rightState);
  }
}


